# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://pay.huihepay.com'
# 汇合是接loki
APP_CONF = {
    '201801041522148831': {
        'API_KEY': '3fa2b9226b80a6dd6ae997df14165ebd',
    },
    '201801221351074886': {
        'API_KEY': '0c6a6201ff5636ad4a0e52be992e9b33',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 2 - 微信扫码
# 3 - QQ钱包
# 4 - 快捷扫码
# 11 - QQWAP
# 6 - 支付宝扫码高费率
# 7 - 微信WAP
# 8 - 百度钱包
# 9 - 京东钱包
# 12 - 京东wap
# 10 - 银联钱包
def _get_pay_type(service):
    if service == 'alipay':
        return '6'
    elif service == 'union':
        return '10'
    elif service == 'qq':  # [2.00 - 5000.00]
        return '11'
    elif service == 'jd':
        return '12'
    else:
        return '7'


def gen_sign_str(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    return s[0:len(s) - 1]


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    params.pop('SignType')
    calculated_sign = generate_sign(gen_sign_str(params) + key)
    if sign != calculated_sign:
        _LOGGER.info("huihepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('AppId', app_id),
        ('Method', 'trade.page.pay'),
        ('Format', 'JSON'),
        ('Charset', 'UTF-8'),
        ('Version', '1.0'),
        ('Timestamp', time.strftime("%Y-%m-%d %H:%M:%S")),
        ('PayType', _get_pay_type(service)),
        ('OutTradeNo', str(pay.id)),
        ('TotalAmount', str(pay_amount)),
        ('Subject', 'charge'),
        ('Body', 'charge'),
        ('NotifyUrl', '{}/pay/api/{}/huihepay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    s = gen_sign_str(parameter_dict)
    parameter_dict['Sign'] = generate_sign(s + api_key)
    parameter_dict['SignType'] = 'MD5'
    _LOGGER.info("huihepay create  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("huihepay create rsp data: %s %s", response.status_code, response.text)
    res_obj = json.loads(response.text)
    return {'charge_info': res_obj['QrCode']}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("huihepay notify data: %s", data)
    _LOGGER.info("huihepay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['OutTradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huihepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['Code']
    trade_no = data['TradeNo']
    total_fee = float(data['TotalAmount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':
        _LOGGER.info('huihepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('AppId', app_id),
        ('Method', 'trade.page.query'),
        ('Format', 'JSON'),
        ('Charset', 'UTF-8'),
        ('Version', '1.0'),
        ('Timestamp', time.strftime("%Y-%m-%d %H:%M:%S")),
        ('OutTradeNo', str(pay_id)),
    ))
    s = gen_sign_str(parameter_dict)
    parameter_dict['Sign'] = generate_sign(s + api_key)
    parameter_dict['SignType'] = 'MD5'
    _LOGGER.info("huihepay query  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        data = json.loads(response.text)['Data']
        trade_status = str(data['State'])
        trade_no = data['TradeNo']
        total_fee = float(data['TotalFee'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 交易状态（2 - 交易中，3 - 交易成功，4 - 交易失败，5 - 交易超时取消）
        if trade_status == '3':
            _LOGGER.info('huihepay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('huihepay data error, status_code: %s', response.status_code)


if __name__ == '__main__':
    app_id = '201801041522148831'
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('AppId', app_id),
        ('Method', 'trade.page.query'),
        ('Format', 'JSON'),
        ('Charset', 'UTF-8'),
        ('Version', '1.0'),
        ('Timestamp', time.strftime("%Y-%m-%d %H:%M:%S")),
        ('OutTradeNo', '1233456'),
    ))
    s = gen_sign_str(parameter_dict)
    parameter_dict['Sign'] = generate_sign(s + api_key)
    parameter_dict['SignType'] = 'MD5'
    print parameter_dict
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    print response.text
    print response.url
